<template>
	<!-- 静态数据 -->
	<el-select
		v-if="selDataType === 'enum'"
		:disabled="!activate"
		:multiple="multiple"
		:placeholder="FieldItem!.TipsText"
		v-model="componentVal"
		clearable
		filterable
		:style="{ width: width }"
		@change="emits('update:modelValue', $event)"
	>
		<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
	</el-select>

	<!-- 动态数据 -->
	<el-select
		v-else-if="selDataType === 'remote'"
		v-model="componentVal"
		:disabled="!activate"
		:multiple="multiple"
		:placeholder="FieldItem!.TipsText"
		:filterable="true"
		:remote="true"
		:loading="loading"
		:style="{ width: width }"
		clearable
		:remote-method="remoteMethod"
		@focus="handleFocus"
		@clear="remoteMethodclear"
		@change="emits('update:modelValue', $event)"
	>
		<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
	</el-select>
</template>
<script setup lang="ts" name="lx-select">
import { TablePageType, TabFieldType } from '/@/components/Linxyun/custom/DataStructs/commontype';
import { ISelectStateType } from './type/lx-select.type';
import EnumOptions from '/@/components/Linxyun/Datas/enum_options.js';
import Lxy_page_event_remote from '../custom/CustomCommon/lxy_page_event_remote.js';
import useElement from './hooks/useElement';
const props = withDefaults(
	defineProps<{
		pageInfo?: TablePageType;
		filterIdx: number;
		located: string;
		modelValue: string;
		FieldItem: TabFieldType | null;
		pageData?: Record<string, any>;
		inputData?: Record<string, any>;
		globalData?: Record<string, any>;
	}>(),
	{ located: 'table', filterIdx: -1, pageData: () => ({}), inputData: () => ({}), modelValue: '', FieldItem: null }
);
const { FieldItem, pageData, inputData, globalData, located } = toRefs(props);
console.log('inputData1111:', inputData);
const emits = defineEmits(['update:modelValue', 'handleClick', 'handleEmitEvent', 'updatePageDataFieldObj']);
const state = reactive<ISelectStateType>({ activate: true, multiple: false, componentVal: '', options: [], rawOptions: [], cascadeObj: {} });
const loading = ref(false);
const width = ref();
const { activate, multiple, componentVal, options } = toRefs(state);
// onBeforeMount(() => {
// 	init();
// });
//

const selDataType = computed(() => {
	if (FieldItem.value?.pageType) {
		if (FieldItem.value.ifStaticOption) {
			return 'enum';
		} else {
			return 'remote';
		}
	} else {
		if (FieldItem.value?.InputType === 'el-select') {
			return 'enum';
		} else if (FieldItem.value?.InputType === 'select_d') {
			return 'remote';
		}
	}
});

const notify = (params: any) => {
	console.log('notify', params);
};

// 设置组件属性
const setActivate = (params: any) => {
	activate.value = params.activate;
};

// 远程搜索下拉
const remoteMethod = async (query: string, key?: string) => {
	console.log('remoteMethod', query, 'key:', key);
	let InputDefine: { [x: string]: any };
	if (FieldItem.value?.pageType && FieldItem.value?.pageType === 'page') {
		InputDefine = {
			event: {
				params: FieldItem.value.dynamicOptions.params,
				url: FieldItem.value.dynamicOptions.url,
			},
			inputdisplay: FieldItem.value.dynamicOptions.label,
			inputflag: FieldItem.value.dynamicOptions.value,
		};
	} else {
		InputDefine = reactive(FieldItem.value?.InputDefine);
	}
	console.log('InputDefineInputDefine', InputDefine);

	if (!InputDefine || !InputDefine.event || !InputDefine.event.url) {
		console.error('[Error]Not define url for select ctrl: ', FieldItem.value!.FieldName);
		return (loading.value = false);
	}
	const { event, inputdisplay, inputflag } = InputDefine;
	const remoteEvent = new Lxy_page_event_remote(event);

	remoteEvent.setDataSrc({ ...props.pageData }, props.inputData, props.globalData || {});
	const params: any = {};
	if (FieldItem.value?.FieldName) {
		params[FieldItem.value!.FieldName] = componentVal.value;
		// params[InputDefine.inputflag] = componentVal.value;
		// isCreate.value = false;
	}
	console.log('select InputDefine.inputflag: ', InputDefine, InputDefine.inputflag)
	if (InputDefine.inputflag) {
		// params[FieldItem.value!.FieldName] = componentVal.value;
		params[InputDefine.inputflag] = componentVal.value;
		// isCreate.value = false;
	}
	if (key) {
		params[key] = query;
	} else {
		params[inputdisplay] = query;
	}
	console.log('select ', params, key, query)
	const result = await remoteEvent.callEvent(params);
	if (!result || !result.Records) {
		console.error('[Error]call remote method fail, itme: ', FieldItem.value?.FieldName);
		return (loading.value = false);
	}
	const doptions = result.Records;
	state.rawOptions = doptions;
	options.value = doptions.map((op: Record<string, any>) => {
		return { label: op[inputdisplay], value: op[inputflag] };
	});
	// console.log('options', options);
	loading.value = false;
};
const isCreate = ref(true);
async function init() {
	// 获取下拉枚举列表
	if (FieldItem.value?.InputDefine?.EnumValue || (FieldItem?.value?.pageType === 'page' && FieldItem?.value?.ifStaticOption)) {
		console.log('EnumOptions');

		options.value = EnumOptions.instance().getOptions(
			FieldItem?.value?.pageType === 'page' ? FieldItem.value.attrs.EnumValue : FieldItem.value.InputDefine.EnumValue
		);
		console.log('option', options.value);
	} else {
		await remoteMethod('');
	}
}
// 绑定值发生变化时更改

watch(
	() => props.modelValue,
	async (newVal) => {
		// console.log('watch select val', newVal, props.modelValue);
		componentVal.value = newVal ?? '';
		if (FieldItem.value?.InputType === 'select_d' && componentVal.value) {
			const { inputflag } = FieldItem.value.InputDefine;

			await init();
			if (inputflag) {
				state.cascadeObj = state.rawOptions?.find((op) => op[inputflag] === componentVal.value) || {};
			}
			emits('updatePageDataFieldObj', state.cascadeObj, `${FieldItem.value.FieldName}Obj`);
		} else {
			// if (FieldItem.value?.DefaultValue && componentVal.value == '') {
			// 	componentVal.value = FieldItem.value?.DefaultValue;
			// }
			init();
		}
	},
	{
		immediate: true,
	}
);
// 清空下拉数据
const remoteMethodclear = () => {
	options.value = [];
	console.log('清空', options.value);
};

// 聚焦时调用
const handleFocus = () => {
	console.log('handleFocus', FieldItem?.value);
	// 不等于级联时调用获取菜单
	// if (options.value.length) return;
	remoteMethod('');
};

const { handleStyle, handleDisable } = useElement(located, FieldItem.value!, componentVal, props);
if (FieldItem.value?.pageType && FieldItem.value.pageType === 'page') {
	activate.value = !FieldItem.value.attrs.disabled;
	width.value = '100%';
} else {
	handleDisable(activate);
	width.value = handleStyle();
}

defineExpose({ notify, setActivate, remoteMethod, init });
</script>
<style></style>
